package com.kzj.laimeimei.request;

import android.text.TextUtils;

import com.ab.util.AbLogUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kzj.laimeimei.activity.GBaseActivity;
import com.kzj.laimeimei.activity.ServerLogActivity;
import com.kzj.laimeimei.global.Constant;
import com.kzj.laimeimei.recyclerCard.basic.MaterialListAdapter;
import com.kzj.laimeimei.recyclerCard.basic.MaterialListView;
import com.kzj.laimeimei.recyclerCard.basic.SuperSwipeRefresh;
import com.kzj.laimeimei.widget.dialog.SweetDialogManager;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

/**
 * RequestServerManager下的实现类，负责总过滤后台接口
 * @author xyg
 *
 */
public class RequestServer implements IRequestServer {

    private static RequestServer instance;
    private static AsyncHttpClient httpClient = null;
    public static int RESULT_FALSE = 0;// 后台返回结果为false
    public static int ERROR_EXCEPTION = -1;// 异常
    public static int ERROR_NULL = -2;// 返回对象为空
    public static int ERROR_JSON_NULL = -3;// 后台返回json字符串为空

    public static String ERROR_TIME_OUT = "网络异常，请检查本地网络";
    public static String ERROR_NULL_TIP = "返回对象为空";
    public static String ERROR_JSON_NULL_TIP = "返回json字符串为空";
    public static String ERROR_SERVER_TIP = "连接服务器失败";
    public static String ERROR_NO_KNOWN_TIP = "未知错误";// 未知错误
    public static String ERROR_ENCODING_TIP = "数据编码格式错误";
    public static String ERROR_JSONSYNTAX_TIP = "网络异常，请重试(JSON语法格式出错)";// JSON语法格式出错
    public static String ERROR_EXCEPTION_TIP = "处理异常";
	private static String boundary;
    private final static char[] MULTIPART_CHARS =
            "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    
    private int firstCount=0;
    private int lastCount=0;
    public static RequestServer getInstance()
    {
        if (instance==null) {
            instance=new RequestServer();
        }
        return instance;
    }
    private static AsyncHttpClient getHttpClient() {
    	
      /*  final StringBuilder buf = new StringBuilder();
        final Random rand = new Random();
        for (int i = 0; i < 30; i++) {
            buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
        }

        boundary = buf.toString();
        */
        if (httpClient == null) {
            httpClient = new AsyncHttpClient();
            httpClient.setTimeout(20000);

        }
     /*   if (App.getInstance().getToken()!=null) {
        	httpClient.addHeader(Constant.SystemContext.TOKEN,AppConfig.getInstance().getToken());
		}*/
   
      //  httpClient.addHeader("Content-Type",  "multipart/form-data; boundary=" + boundary);
        return httpClient;
    }
/*    @Override
    public <T extends IBaseResponse> void handleMethod(String url,
                                                       RequestParams requestParams, final Class<T> instanceClass,
                                                       final ICallBackForRequestServer<T> callBack) {
    	
		ServerLogActivity.saveRequest2File(requestParams, url);
    //	 getHttpClient().post(AppConfig.getInstance(),url, httpentity, "",
		 getHttpClient().post(url,  requestParams,
                new AsyncHttpResponseHandler(){
                    String content = "";
                    @Override
                    public void onSuccess(int arg0, Header[] headers, byte[] arg2) {
                        // TODO Auto-generated method stub53ec5c9ba310221b619d07e4
                        try {
                        	//如果token为空，重新获取
                        	if (AppConfig.getInstance().getToken()==null) {
								for (int i = 0; i < headers.length; i++) {
									if (headers[i].getName().equals(Constant.SystemContext.TOKEN)) {
										AppConfig.getInstance().setToken(headers[i].getValue());
									}
								}
							}
                            content = new String(arg2, GConstant.encodeStyle);
                            if (!TextUtils.isEmpty(content)) {
                            	//这里解析jsonRin
   
                                T result = JSON.parseObject(content, instanceClass);
                                
                                if (result != null) {
                                    if (GConstant.SuccessState.equals(result.getCode())) {
                                        callBack.onSuccess(result);
                                    } else {
                                        callBack.onFail(
                                                RESULT_FALSE,
                                                result.getMessage() != null
                                                        && !TextUtils.isEmpty(result
                                                        .getMessage().trim()) ? result
                                                        .getMessage()
                                                        : ERROR_NO_KNOWN_TIP,content);
                                    }
                                } else {
                                    callBack.onFail(ERROR_NULL,
                                            ERROR_NULL_TIP,content);
                                }
                            } else {
                            	StackTraceElement traceElement = ((new Exception()).getStackTrace())[1]; 
        						AbLogUtil.e(traceElement.getClassName()+"-"+traceElement.getMethodName(), "返回的信息为空");
                                callBack.onFail(ERROR_JSON_NULL,
                                        ERROR_JSON_NULL_TIP,content);

                            }

                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (Exception e) {
                            content += ",异常信息：" + e.getMessage();
                            e.printStackTrace();
                            callBack.onFail(ERROR_EXCEPTION,
                                    ERROR_EXCEPTION_TIP,content);
                            
                        } finally {
								ServerLogActivity.saveResponse2File(content);
							

                        }
                      //  super.onSuccess(arg0, arg1, arg2);
                    }
                    @Override
                    public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                                          Throwable arg3) {
                        try {
                            if (arg2!=null) {
                                content = new String(arg2, GConstant.encodeStyle);
                                if (!TextUtils.isEmpty(content)) {
                                	BaseResponse baseResponse=JSONObject.parseObject(content, BaseResponse.class);
                                	if (baseResponse!=null && Constant.SystemContext.LoginFail.equals(baseResponse.getCode())) {
                                	   Intent intent = new Intent();
                         			   intent.setClass(AppConfig.getInstance(), LoginActivity_new.class);
                         			   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
                         			   AppConfig.getInstance().startActivity(intent);
									}
								}
                                
                                callBack.onFail(ERROR_NULL, ERROR_NULL_TIP,content);
                                AbToastUtil.showToast(AppConfig.getInstance().getApplicationContext(), ERROR_NULL_TIP);
                            }else
                            {
                            	 callBack.onFail(ERROR_NULL, ERROR_NULL_TIP,"");
                            }
                            

                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }finally{
                        }
                        // TODO Auto-generated method stub
                        //callBack.onFail(type, errorMsg, json);
                        //ServerLogActivity.saveResponse2File(arg3.getMessage());
                     //   super.onFailure(arg0, arg1, arg2, arg3);
                    }
                });
    }*/
    @Override
    public <T extends IBaseResponse> void handleMethod(final GBaseActivity gBaseActivity,final MaterialListView materialListView,final SuperSwipeRefresh swipeRefresh,final boolean isLoadMore,String url,
                                                       RequestParams requestParams, final Class<T> instanceClass,
                                                       final ICallBackForRequestServer<T> callBack) {
    	
    	if (!isLoadMore) {
			if (swipeRefresh!=null) {
				swipeRefresh.setPage(1);
			}
		}
    	//listview数据不为空的操作
    	if (materialListView!=null) {
			MaterialListAdapter materialListAdapter=(MaterialListAdapter) materialListView.getAdapter();
			if (materialListAdapter.getAllList().size()>0) {
				firstCount=materialListAdapter.getAllList().size();
				if (gBaseActivity!=null) {
					gBaseActivity.dismissDialog();
				}
				
				//如果有数据，不执行动画
				materialListView.setItemAnimator(null);
			}else
			{
				if (gBaseActivity!=null) {
					gBaseActivity.showLoadingDialog();
				}
			}
		}else
		{
			if (gBaseActivity!=null) {
				gBaseActivity.showLoadingDialog();
			}
		}
		ServerLogActivity.saveRequest2File(requestParams, url);
    //	 getHttpClient().post(AppConfig.getInstance(),url, httpentity, "",
		 getHttpClient().post(url,  requestParams,
                new AsyncHttpResponseHandler(){
                    String content = "";
                    @Override
                    public void onSuccess(int arg0, Header[] headers, byte[] arg2) {
                    	
                        // TODO Auto-generated method stub53ec5c9ba310221b619d07e4
                        try {
                        	if (gBaseActivity!=null) {
                        		
            					gBaseActivity.dismissDialog();
            				}
                        	//如果token为空，重新获取
                        
							/*	for (int i = 0; i < headers.length; i++) {
									if (App.getInstance().getToken()==null) {
										if (headers[i].getName().equals(Constant.SystemContext.TOKEN)) {
											AppConfig.getInstance().setToken(headers[i].getValue());
										}
									}
									if (headers[i].getName().equals("Set-Cookie")) {
										AppConfig.getInstance().setCookie(headers[i].getValue().split(";")[0]);
									}
								}*/
							
                            content = new String(arg2, Constant.SystemContext.encodeStyle);
                            if (!TextUtils.isEmpty(content)) {
                            	//这里解析jsonRin
   
                                T result = JSON.parseObject(content, instanceClass);
                                
                                if (result != null) {
                                    if (Constant.SystemContext.SuccessState.equals(result.getCode())) {
                                    	
                                        callBack.onSuccess(result);
                                        if (materialListView!=null) {
	                                        MaterialListAdapter materialListAdapter=(MaterialListAdapter) materialListView.getAdapter();
	                                        lastCount=materialListAdapter.getAllList().size();
                                        }
                                    } else {
                                        callBack.onFail(
                                                RESULT_FALSE,
                                                result.getMessage() != null
                                                        && !TextUtils.isEmpty(result
                                                        .getMessage().trim()) ? result
                                                        .getMessage()
                                                        : ERROR_NO_KNOWN_TIP,content);
                                    }
                                } else {
                                    callBack.onFail(ERROR_NULL,
                                            ERROR_NULL_TIP,content);
                                }
                            } else {
                            	StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];
        						AbLogUtil.e(traceElement.getClassName() + "-" + traceElement.getMethodName(), "返回的信息为空");
                                callBack.onFail(ERROR_JSON_NULL,
                                        ERROR_JSON_NULL_TIP,content);
                                
                            }

                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (Exception e) {
                            Writer writer = new StringWriter();
                            PrintWriter printWriter = new PrintWriter(writer);
                            e.printStackTrace(printWriter);
                            Throwable cause = e.getCause();
                            while (cause != null) {
                                cause.printStackTrace(printWriter);
                                cause = cause.getCause();
                            }
                            printWriter.close();
                            content += ",异常信息：" + writer.toString();
                            e.printStackTrace();
                            callBack.onFail(ERROR_EXCEPTION,
                                    ERROR_EXCEPTION_TIP,content);
                            
                        } finally {
                        	
                        	if (swipeRefresh!=null) {
                        		//加载更多多了一个小圈
                            	if (isLoadMore) {
                            		lastCount++;
    							}
                            	AbLogUtil.e("first-last", "first-" + firstCount + "-last-" + lastCount);
                            	swipeRefresh.updateSwipeRefreshSuccess(lastCount-firstCount,isLoadMore);
    								
							}
                        	ServerLogActivity.saveResponse2File(content);
                        }
                      //  super.onSuccess(arg0, arg1, arg2);
                    }
                    @Override
                    public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                                          Throwable arg3) {
                        try {
                        	if (gBaseActivity!=null) {
            					//gBaseActivity.dismissDialog();
            				}
                            if (arg2!=null && arg2.length>0) {
                                content = new String(arg2, Constant.SystemContext.encodeStyle);
                                if (!TextUtils.isEmpty(content)) {
                                	BaseResponse baseResponse= JSONObject.parseObject(content, BaseResponse.class);
                                	/*if (baseResponse!=null && Constant.SystemContext.LoginFail.equals(baseResponse.getCode())) {
                                	   Intent intent = new Intent();
                         			   intent.setClass(AppConfig.getInstance(), LoginActivity_new.class);
                         			   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                         			   AppConfig.getInstance().startActivity(intent);
									}*/
								}
                               
                                callBack.onFail(ERROR_NULL, ERROR_NULL_TIP,content);
                                SweetDialogManager.getInstance().showDialogByErrorTitleText(gBaseActivity, ERROR_NULL_TIP,  false, false);
                               // AbToastUtil.showToast(AppConfig.getInstance().getApplicationContext(), ERROR_NULL_TIP);
                            }else
                            {
                            	 callBack.onFail(ERROR_NULL, ERROR_TIME_OUT,"");
                            	 SweetDialogManager.getInstance().showDialogByErrorTitleText(gBaseActivity, ERROR_TIME_OUT,  false, false);
                            	 //AbToastUtil.showToast(AppConfig.getInstance().getApplicationContext(), ERROR_TIME_OUT);
                            }
                            

                        } catch (Exception e) {
                        	SweetDialogManager.getInstance().showDialogByErrorTitleText(gBaseActivity, ERROR_EXCEPTION_TIP,  false, false);
                        	//AbToastUtil.showToast(AppConfig.getInstance(),"baseResponse转换错误"+ e.toString());
                            e.printStackTrace();
                        }
//                        catch (JSONException e) {
//                       	 e.printStackTrace();
//						}
                        finally{
                        	if (swipeRefresh!=null) {
                        		//加载更多多了一个小圈
                            	if (isLoadMore) {
                            		lastCount++;
    							}
                            	swipeRefresh.updateSwipeRefreshSuccess(lastCount - firstCount, isLoadMore);

							}
                            ServerLogActivity.saveResponse2File(content);
                        }
                        // TODO Auto-generated method stub
                        //callBack.onFail(type, errorMsg, json);
                        //ServerLogActivity.saveResponse2File(arg3.getMessage());
                     //   super.onFailure(arg0, arg1, arg2, arg3);
                    }
                });
    }
	/*@Override
	public <T extends IBaseResponse> void handleMethodMultipart(String url,
			HttpEntity httpentity, final Class<T> instanceClass,
			final ICallBackForRequestServer<T> callBack) {
		
	//	ServerLogActivity.saveRequest2File(requestParams, url);
    //	HttpEntity httpentity= makeMultipartEntity(null, null);
    	 getHttpClient().post(App.getInstance(),url, httpentity, "",
	//	 getHttpClient().post(url,  requestParams,
                new AsyncHttpResponseHandler(){
                    String content = "";
                    @Override
                    public void onSuccess(int arg0, Header[] headers, byte[] arg2) {
                        // TODO Auto-generated method stub53ec5c9ba310221b619d07e4
                        try {
                        	//如果token为空，重新获取
                        	*//*if (App.getInstance().getToken()==null) {
								for (int i = 0; i < headers.length; i++) {
									if (headers[i].getName().equals(Constant.SystemContext.TOKEN)) {
										AppConfig.getInstance().setToken(headers[i].getValue());
									}
								}
							}*//*
                            content = new String(arg2, Constant.SystemContext.encodeStyle);
                            if (!TextUtils.isEmpty(content)) {
                            	//这里解析jsonRin
   
                                T result = JSON.parseObject(content, instanceClass);
                                
                                if (result != null) {
                                    if (Constant.SystemContext.SuccessState.equals(result.getCode())) {
                                        callBack.onSuccess(result);
                                    } else {
                                        callBack.onFail(
                                                RESULT_FALSE,
                                                result.getMessage() != null
                                                        && !TextUtils.isEmpty(result
                                                        .getMessage().trim()) ? result
                                                        .getMessage()
                                                        : ERROR_NO_KNOWN_TIP,content);
                                    }
                                } else {
                                    callBack.onFail(ERROR_NULL,
                                            ERROR_NULL_TIP,content);
                                }
                            } else {
                            	StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];
        						AbLogUtil.e(traceElement.getClassName() + "-" + traceElement.getMethodName(), "返回的信息为空");
                                callBack.onFail(ERROR_JSON_NULL,
                                        ERROR_JSON_NULL_TIP,content);
                            }

                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (Exception e) {
                            content += ",异常信息：" + e.getMessage();
                            e.printStackTrace();
                            callBack.onFail(ERROR_EXCEPTION,
                                    ERROR_EXCEPTION_TIP,content);
                        } finally {
							
								ServerLogActivity.saveResponse2File(content);
							

                        }
                      //  super.onSuccess(arg0, arg1, arg2);
                    }
                    @Override
                    public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                                          Throwable arg3) {
                        try {
                            if (arg2!=null) {
                                content = new String(arg2, Constant.SystemContext.encodeStyle);
                                callBack.onFail(ERROR_NULL, ERROR_NULL_TIP,content);
                                AbToastUtil.showToast(App.getInstance().getApplicationContext(), ERROR_NULL_TIP);
                            }else
                            {
                            	 callBack.onFail(ERROR_NULL, ERROR_TIME_OUT,"");
                            	 AbToastUtil.showToast(App.getInstance().getApplicationContext(), ERROR_TIME_OUT);
                            }
                            

                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        // TODO Auto-generated method stub
                        //callBack.onFail(type, errorMsg, json);
                        //ServerLogActivity.saveResponse2File(arg3.getMessage());
                     //   super.onFailure(arg0, arg1, arg2, arg3);
                    }
                });
		
	}*/

   
}
